snowsoft.gibay._LOG.info("Loading class, 'snowsoft.gibay.ViewItemDetail'");

/**
 * Calls GetItem,GetFeedback and GetAllBidders data services
 * Handles ItemDetail dialog's behavior and UI updates
 * @author digitalghost.liu@gmail.com 
 */
jsx3.lang.Class.defineClass("snowsoft.gibay.ViewItemDetail", null, [], function(ViewItemDetail) {

	//Varibles for photo page split
	var _photoIndex = 0;
	
	//varibles for current view window type,like a dialog or a new window
	var _windowType = "dialog";//enum:{window,dialog};

	//Timer id for auto update remaining time timer
	var _remainingTimerId = null;

	//shortcut to package
	var gibay = snowsoft.gibay;

	
	
 	//private method: for refresh the current item detail view
	var _updateViewItem = function(itemID){
		gibay.APP.getJSXByName("blkDetailContainer").showMask("Loading item detail...");
		try{	
			var objService = null;
			objService = gibay.APP.loadResource("getitem_xml");
			objService.setOperation("GetItem");
			objService.startTime = (new Date()).valueOf();	
			objService.itemID = itemID;
			objService.subscribe(jsx3.net.Service.ON_SUCCESS,_onUpdateViewItemSuccess);	
			objService.subscribe(jsx3.net.Service.ON_ERROR,_onUpdateViewItemError);
			gibay._LOG.info("Call GetItem service....");
			objService.doCall();
		}catch(e){
			var objError = jsx3.lang.NativeError.wrap(e);
			gibay._LOG.error(objError.getMessage());		
		}

	};
	var _onUpdateViewItemSuccess = function(objEvent){
		var tTotal = ((new Date()).valueOf() - objEvent.target.startTime) / 1000;
		//alert(objEvent.target.getInboundDocument());
		gibay._LOG.info("Call GetItem service successful.."+tTotal+" secs");
		gibay.APP.getJSXByName("blkDetailContainer").hideMask();
		
		var objDoc = gibay.APP.getCache().getDocument("MODEL_ItemDetail");
		var dlgItemDetail = gibay.APP.getJSXByName("dlgItemDetail");

		//for price info and bid info at right side
		var bidTotalPrice = parseFloat(objDoc.getAttribute("MinimumToBid"))+shippingCost;
		var nowTotalPrice = parseFloat(objDoc.getAttribute("CurrentPrice"))+shippingCost;
		dlgItemDetail.getDescendantOfName("lblBidTotalPrice").setText(bidTotalPrice+"+",true);
		dlgItemDetail.getDescendantOfName("lblNowTotalPrice").setText(nowTotalPrice,true);

		//for shipping tab
		var shippingCost = parseFloat(objDoc.getAttribute("ShippingServiceCost"));
		if( shippingCost != 0){
			dlgItemDetail.getDescendantOfName("tabShipping").setText("Shipping($"+shippingCost+")",true);
		}

		//for photo tab
		var photos = objDoc.selectNodes("//record");
		dlgItemDetail.getDescendantOfName("tabPhoto").setText("Photo("+photos.size()+")",true);

		//restore dialog's all gui component default state
		dlgItemDetail.getDescendantOfName("btnAddWatch").setEnabled(jsx3.gui.Form.STATEENABLED,true);
		dlgItemDetail.getDescendantOfName("tabPhoto").doShow();
		ViewItemDetail.goPhoto(0);
		
		//next phase,load seller's infomation
		_updateSellerInfo();
		//next phase,load item's bid infomation	
		_updateBidInfo();

		//init remaining timer,this timer for update the remaining time dynamiclly
		_remainingTimerId = window.setInterval(_updateRemainingTime,2000);
		
	};
	var _onUpdateViewItemError = function(objEvent){
		var tTotal = ((new Date()).valueOf() - objEvent.target.StartTime) / 1000;
    	giaby._LOG.info("Get service error, 'Response':\n__________________\n" + objEvent.target.getInboundDocument() + "\n__________________\n response time: " + tTotal + " seconds.");
    	gibay.APP.getJSXByName("blkDetailContainer").hideMask();
	};
	
	
	//private method for auto update remaining time
	var _updateRemainingTime = function(){
		//code below is low tech to parse time format from ebay's response
		var dlgItemDetail = gibay.APP.getJSXByName("dlgItemDetail");
		var itemRecord = dlgItemDetail.itemRecord;//item record for current item the dialog displayed
		var remainingTimeStatus = "";	
		var strStandard = itemRecord.EndTime.replace(/([0-9]+)-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})\.[0-9]*Z/g,'$1/$2/$3 $4:$5:$6');
		var endTime = Date.parse(strStandard);
		var nowTime = new Date().getTime();
		var timeSpan = endTime - nowTime;
		if(timeSpan<=0){
			remainingTimeStatus = "Ended";
		}else{
			var minutes = 1000 * 60;
			var hours = minutes * 60;
			var days = hours * 24;
			var years = days * 365;
			var d = parseInt(timeSpan/days);	
			var h = 0;
			var m = 0;
			var s = 0;

			gibay.APP.getJSXByName("lblEndTime").setText(timeSpan,true);			
			timeSpan = (d!=0)?(timeSpan%days):timeSpan;
			h = parseInt(timeSpan/hours);
			timeSpan = (h!=0)?(timeSpan%hours):timeSpan;
			m = parseInt(timeSpan/minutes);
			timeSpan = (m!=0)?(timeSpan%minutes):timeSpan;
			s = parseInt(timeSpan/1000);
				
			remainingTimeStatus = (d!=0)?(remainingTimeStatus+d.toString()+' days '):remainingTimeStatus;
			remainingTimeStatus = (h!=0)?(remainingTimeStatus+h.toString()+':'):remainingTimeStatus;
			remainingTimeStatus = (m!=0)?(remainingTimeStatus+m.toString()+':'):remainingTimeStatus;
			remainingTimeStatus = (s!=0)?(remainingTimeStatus+s.toString()+''):remainingTimeStatus;

		}
		gibay.APP.getJSXByName("lblEndTime").setText(remainingTimeStatus,true);			
	};

	//private method for photo page navigation 
	var _updatePhotoPageNav = function(){
		//hack into gi's JSX Object fx to capture the onload event of <img> tag
		var objJSXImgPhoto = gibay.APP.getJSXByName("imgPhoto");		
		window.document.getElementById(objJSXImgPhoto.getId()).firstChild.onload = function(){
			objJSXImgPhoto.repaint();
		}	
		
		var blkPhotoPage = gibay.APP.getJSXByName("blkPhotoPage");
		var objDoc = gibay.APP.getCache().getDocument("MODEL_ItemDetail");
		var photos = objDoc.selectNodes("//record");//a xml node collection.getItem(0).getAttribute("jsxid");
		var photoCount = photos.size();
		if(photoCount <= 1){
			blkPhotoPage.setText("",true);
			return;	
		}
		var html = '';
		if(_photoIndex <= 0){
			html += '<span>&lt;Prev</span>';
		}else{
			html += '<a href="javascript:{void(0);}" onclick="snowsoft.gibay.ViewItemDetail.goPhoto('+(_photoIndex-1)+')">&lt;Prev</a>';
		}
		html += '<span style="margin-left:4px;">|</span>';
		html += '<span style="margin-left:4px;margin-right:4px;">' + (_photoIndex+1) + '&nbsp;of&nbsp;' + photoCount + '&nbsp;photos&nbsp;</span>';
		html += '<span style="margin-right:4px;">|</span>';
		if(_photoIndex >= (photoCount - 1)){
			html += '<span>Next&gt;</span>';
		}else{
			html += '<a href="javascript:{void(0);}" onclick="snowsoft.gibay.ViewItemDetail.goPhoto('+(_photoIndex+1)+')">Next&gt;</a>';
		}
		blkPhotoPage.setText(html,true);
			
	};
	
	//private method for update seller's ratings
	var _updateSellerInfo = function(){
		try{	
			var objService = null;
			objService = gibay.APP.loadResource("getfeedback_xml");
			objService.setOperation("GetFeedback");
			objService.startTime = (new Date()).valueOf();	
			objService.userID = gibay.APP.getJSXByName("blkSellerID").getText(); 
			objService.subscribe(jsx3.net.Service.ON_SUCCESS,_onUpdateSellerInfoSuccess);	
			objService.subscribe(jsx3.net.Service.ON_ERROR,_onUpdateSellerInfoError);
			gibay._LOG.info("Call GetFeedback service....");
			objService.doCall();
		}catch(e){
			var objError = jsx3.lang.NativeError.wrap(e);
			gibay._LOG.error(objError.getMessage());	
		}

	};
	var _onUpdateSellerInfoSuccess = function(objEvent){
		var tTotal = ((new Date()).valueOf() - objEvent.target.startTime) / 1000;
		gibay._LOG.info("Call GetFeedback service successful.."+tTotal+" secs");
		
		var objDocSellerRating = gibay.APP.getCache().getDocument("MODEL_SellerRating");
		//you could uncomment code below,you could get a unexpect result,is this gi's chart component bug???
		//gibay.APP.getJSXByName("chartSeller").repaint();
	
	};
	var _onUpdateSellerInfoError = function(objEvent){
		var tTotal = ((new Date()).valueOf() - objEvent.target.StartTime) / 1000;
    	giaby._LOG.info("Get service error, 'Response':\n__________________\n" + objEvent.target.getInboundDocument() + "\n__________________\n response time: " + tTotal + " seconds.");
	};

	//private method for update bidder's ratings
	var _updateBidInfo = function(){
		
		try{	
			var objService = null;
			objService = gibay.APP.loadResource("getallbidders_xml");
			objService.setOperation("GetAllBidders");
			objService.startTime = (new Date()).valueOf();	
			objService.itemID = gibay.APP.getJSXByName("dlgItemDetail").itemRecord.ItemID.toString(); 
			objService.subscribe(jsx3.net.Service.ON_SUCCESS,_onUpdateBidInfoSuccess);	
			objService.subscribe(jsx3.net.Service.ON_ERROR,_onUpdateBidInfoError);
			gibay._LOG.info("Call GetAllBidders service....");
			objService.doCall();
		}catch(e){
			var objError = jsx3.lang.NativeError.wrap(e);
			gibay._LOG.info(objError.getMessage());	
		}

	};
	var _onUpdateBidInfoSuccess = function(objEvent){
		var tTotal = ((new Date()).valueOf() - objEvent.target.startTime) / 1000;
		gibay._LOG.info("Call GetAllBidders service successful.."+tTotal+" secs");
		var objDocBidInfo = gibay.APP.getCache().getDocument("MODEL_BidInfo");
		//update bids tab's title
		var bids = objDocBidInfo.selectNodes("//record");
		gibay.APP.getJSXByName("dlgItemDetail").getDescendantOfName("tabBids").setText("Bids("+bids.size()+")",true);
		gibay.APP.getJSXByName("chartBids").repaint();
		
	};
	var _onUpdateBidInfoError = function(objEvent){
		var tTotal = ((new Date()).valueOf() - objEvent.target.StartTime) / 1000;
    	giaby._LOG.info("Get service error, 'Response':\n__________________\n" + objEvent.target.getInboundDocument() + "\n__________________\n response time: " + tTotal + " seconds.");
	};

	//window swap function has some bug hasn't been fixed,plz help me to find where's the problem.
	//I just copy the code form sample,but code here couldn't work successfully..too strange.
	ViewItemDetail.swapWindow = function(){
		gibay._LOG.info("window swap function invoked.");
 		// get the pane to be swapped,and its parent
    	var swapPane = gibay.APP.getJSXByName("blkDetailContainer");
    	var currentParent = swapPane.getParent();

    	if (currentParent.getName() == "dlgItemDetail") {
      		// if the parent is part of the main application, get or create the window
      		var w = gibay.APP.getAppWindow("swapWin");
      		if (w == null) {
        		w = gibay.APP.createAppWindow("swapWin");
        		w.setHeight(400);
        		w.setWidth(500);
        		w.setTitle("Swap Window");
      		}

      		// subscribe to the window closing event to return the content
      		// to the application when the windowisclosed
			// problem here is I couldn't capture the new window's close event.
      		w.subscribe(jsx3.gui.Window.WILL_CLOSE,ViewItemDetail,ViewItemDetail.swapWindow);
      		// now move the pane to the window
      		w.getRootBlock().adoptChild(swapPane);

      		//and show the window if it isn'talready visible
      		if (!w.isOpen()) {
        		w.open();
      		}
      		w.focus();
    	} else {
      		// else if the parent is the root block of the window
      		var w = gibay.APP.getAppWindow("swapWin");
      		if(w) {
        		// unsubscribe fromthe windowclosing event
        		//w.unsubscribe(jsx3.gui.Window.WILL_CLOSE,ViewItemDetail,ViewItemDetail.swapWindow);
        		w.unsubscribe(jsx3.gui.Window.WILL_CLOSE,this,this.swapWindow);
      		}

      		// move the content backto the application
      		gibay.APP.getJSXByName("dlgItemDetail").adoptChild(swapPane);

      		// and close the window
      		w.close();
    	}
				
	};

	//method to handle the photo navigation	
	ViewItemDetail.goPhoto = function(photoIndex){
		gibay._LOG.info("Go to show the photo at index "+photoIndex);
		_photoIndex = photoIndex;
		var objDoc = gibay.APP.getCache().getDocument("MODEL_ItemDetail");
		var photos = objDoc.selectNodes("//record");//a xml node collection.getItem(0).getAttribute("jsxid");
		var photo = photos.getItem(photoIndex);
		if(photo != null){
			gibay.APP.getJSXByName("imgPhoto").setSrc(photo.getAttribute("jsxtext"));
			gibay.APP.getJSXByName("imgPhoto").repaint();
		};
		_updatePhotoPageNav();	
	};
	
	//method to handle the item detail dialog's initialization
	ViewItemDetail.initDetail = function(objEvent){
		gibay._LOG.info("View item detail about itemId "+objEvent.itemRecord.ItemID);
		try{
			var itemRecord = objEvent.itemRecord;
			var blkRootContainer = gibay.APP.getRootBlock();
			var dlgItemDetail = gibay.APP.getJSXByName("dlgItemDetail");
			if(!dlgItemDetail){
				dlgItemDetail = blkRootContainer.loadAndCache("components/itemDetail.xml",false);
				var pos = blkRootContainer.getAbsolutePosition();
				dlgItemDetail.setHeight(parseInt(pos.H * 0.85));
				dlgItemDetail.setWidth(parseInt(pos.W * 0.85),true);
				blkRootContainer.paintChild(dlgItemDetail);
			};
			dlgItemDetail.itemRecord = itemRecord;//item record for current item the dialog displayed
			dlgItemDetail.setDisplay('block',true);
		}catch(e){
			var objError = jsx3.lang.NativeError.wrap(e);
			gibay._LOG.error(objError.getMessage());	
		}
		gibay.ModelManager.addRecentItem(itemRecord);	
		_updateViewItem(itemRecord.ItemID);//call method to refresh item detail view	
	}	


});

//subscribe handler method to relevant events
snowsoft.gibay.APP.subscribe(snowsoft.gibay.Event.ON_VIEWITEM,snowsoft.gibay.ViewItemDetail.initDetail);

